<?php 
if (!defined('BASEPATH')) exit('No direct access allowed.'); 

class MY_Controller extends CI_Controller {

	protected $ci;
	public $user_id;
	
    public function __construct() { 
        parent::__construct();
		
		$this->load->database();
		$this->load->helper('url');
		
		$this->load->helper('Nets');
		$this->load->helper('Functions');
		$this->load->helper('Constants');
		
		
		$this->user_id = 0;
		$this->admin = array();
		$this->privs = '';
		
		$this->CheckLogin();
		
		$this->file_recovery();//文件定时回收
		
		$this->load->dmodel('admin_logs','admin_logs');
    } 


	function CheckLogin(){		

		//$token = 'Umg3dWJmcDdwYnVPYVpKd3JSZVM5Z3E0MWY2T0hjTWdOZ2NXaVlGMno=';//$this->input->post('token');
		$token = $this->input->post('token',null,'');
		$token_time = $this->input->post('token_time',null,0);
		$this->load->model('User/AdminModel','AdminModel');
		$user = $this->AdminModel->token_get_user($token,$token_time);

		if(!$user){
			$this->err_out('token错误',401);			
		}
		$this->user_id = $user['id'];
		$this->admin = $user;
		
		
		//获取所属公司
		$this->load->model('User/companyModel','companyModel');
		$company = $this->companyModel->name_get_data($user['company']);
		
		
		
		$this->load->dmodel('priv_group','priv_group');
		$res = $this->priv_group->getAll(array('is_enable'=>1));
		
		
		
		//获取权限组的权限
		$privs = array();
		$querys = array();
		$actions = array();
		
		if($company){
			$querys[] = $company['id'];
		}
		
		
		foreach($res as $val){
			$ls_ids = explode(',',$val['ids']);
			if(in_array($this->user_id,$ls_ids)){
				$ls_privs = explode(',',$val['privs']);
				$privs = array_merge($privs,$ls_privs);
				
				$ls_querys = explode(',',$val['querys']);
				$querys = array_merge($querys,$ls_querys);
				
				$ls_actions = explode(',',$val['actions']);
				$actions = array_merge($actions,$ls_actions);
			}
		}
		$privs = array_unique($privs);
		$this->privs = implode(',',$privs);
		
		
		$querys = array_unique($querys);
		$this->querys = implode(',',$querys);
		
		$actions = array_unique($actions);
		$this->actions = implode(',',$actions);
	}
	
	
    public function out($data=array()) {
		$time = time();
       $arr = array('result_code'=>0,'message'=>'','data'=>'','time'=>$time);
	   
	   foreach($data as $key=>$val){
		   $arr[$key] = $val;
	   }
	   echo json_encode($arr);
	   exit;
    }
	
	public function data_out($data=array(),$message="获取数据成功"){
		
		$arr = array('result_code'=>0,'message'=>$message,'data'=>$data);
	    $this->out($arr);
	}
	public function err_out($message,$result_code=1) {
       $arr = array('result_code'=>$result_code,'message'=>$message);
	   $this->out($arr);
    }
	
	
	
	function CheckData($arr=array(),$data=array(),$is_empty=false){
		//验证参数
		$this->load->library('form_validation');
		
		$config = array();
		
		
		if($is_empty){
			foreach($data as $key=>$val){
				$data[$key] = !empty($val)?$val:'';
			}
		}
		
		foreach($arr as $key=>$val){
			if(is_array($val)){

				
				$ls_arr = array();
				$errors = array();
				
				foreach($val as $k=>$v){
					$ls_arr[] = $k;
					$ls_key = preg_replace("/\[.*/",'',$k);
					$errors[$ls_key] = $v;
				}
				$rules = implode('|',$ls_arr);
			}
			else{
				$rules = 'required';
				$errors = array(
					$rules =>$val
				);
			}
			
			$config[] = array(
					'field' => $key,
					'label' => $key,
					'rules' => $rules,
					'errors' => $errors,
				);
		}
		
		$this->form_validation->set_data($data);
		$this->form_validation->set_rules($config);

		if($this->form_validation->run() === FALSE){
			$err_arr = $this->form_validation->error_array();
			
			return implode(PHP_EOL,$err_arr);
        }
		return false;
	}
	
	function data_filter($data,$arr=null,$no_input=array()){
		$ls_arr = array();
		
		if(is_array($arr)){
			foreach($arr as $key=>$val){
				if(isset($data[$val])){
					$ls_arr[$val] = $data[$val];
				}
			}
		}
		else{
			if(is_array($no_input)){
				foreach($no_input as $key=>$val){
					if(isset($data[$val])){
						unset($data[$val]);
					}
				}
			}
			$ls_arr = $data;
		}
		
		return $ls_arr;
	}
	
	public static function xmlToEncode($arr){
		//准备一个接收的空数组
		$xml='';
		//将这个数组的键，作为节点名称，值作为内容
		foreach ($arr as $key => $value) {
			/*约定一个规则，如果键是数字的话，格式为<item id='5'>aaa</item>*/
			if(is_numeric($key)){
				$attr	=	" id='{$key}'";//属性的值需要带上引号，不然报错
				$key	=	'item';
			}

			$xml.="<{$key}{$attr}>";
			//如果$value的值是个多维数组的话，需要递归遍历
			$xml.=is_array($value) ? self::xmlToEncode($value) : $value;	
			$xml.="</{$key}>";
		}
		return $xml;
	}
	
	//$is_bl 是否整数保留小数
	function toFloat($val,$num=2,$is_bl=false){
		
		if($is_bl){
			return sprintf("%.{$num}f", $val); 
		}
		$fg = explode('.',(string)$val);
		if(count($fg)<=1){
			return $val;
		}
		if(strlen($fg[1])<$num){
			return $val;
		}
		
		return sprintf("%.{$num}f", $val); 
	}
	
	function file_recovery(){
		$tmpdir = FCPATH . 'res/tmp';
		
		if(!is_dir($tmpdir))return false;
		
		$handle = opendir($tmpdir);
		$time = time();

		if($handle){
			while(($fl = readdir($handle)) !== false){
				$temp = $tmpdir.DIRECTORY_SEPARATOR.$fl;
				//如果不加  $fl!='.' && $fl != '..'  则会造成把$dir的父级目录也读取出来
				if(is_dir($temp)){
					continue;
				}
				$ftime = filemtime($temp);
				if($time>$ftime+3600){
					@unlink($temp);
				}
			}
		}
	}
	
	function add_log($msg,$module='admin'){
		$admin_id = $this->user_id;
		
		$admin_name = '';
		if($admin_id>0){
			$admin_name = !empty($this->admin['nickname'])?$this->admin['nickname']:$this->admin['username'];
		}
		
		$ip = getIp();
		
		$time = time();
		$arr = array(
			'admin_id'=>$admin_id,
			'admin_name'=>$admin_name,
			'msg'=>$msg,
			'addtime'=>$time,
			'module'=>$module,
			'ip'=>$ip
		);
		$this->admin_logs->add($arr);
		return true;
	}
	
	function check_priv($code){//验证权限
		$privs = explode(',',$this->privs);
		if(in_array('All',$privs)){
			return true;
		}
		$fg = explode('|',$code);
		foreach($fg as $val){
			if(empty($val)){
				continue;
			}
			if(in_array($val,$privs)){
				return true;
			}
		}
		return false;
	}
	
} 

include(APPPATH.'core/MY_Common.php');